import {defineStore} from "pinia";
import {ref, computed} from 'vue';

export const useCartStore = defineStore('cart', () => {
    const cartList = ref([])
    const addCart = (goods) => {
        const item = cartList.value.find((item) => goods.skuId === item.skuId)
        if (item) {
            item.count++
        } else {
            cartList.value.push(goods)
        }
    }
    const delCart = (skuId) => {
        // splice 或者 filter
        const idx = cartList.value.findIndex((item) => item.skuId === skuId)
        cartList.value.splice(idx, 1);
    }
    const allCount = computed(() => cartList.value.reduce((a, c) => a + c.count, 0))
    const allPrice = computed(() => cartList.value.reduce((a, c) => a + c.price * c.count, 0))
    const singCheck = (skuId, selected) => {
        const item = cartList.value.find((item) => item.skuId === skuId)
        item.selected = selected
    }
    const isAll = computed(() => cartList.value.every((item) => item.selected))
    const allCheck = (selected) => {
        cartList.value.forEach(item => item.selected = selected)
    }
    const selectedCount = computed(() => {
        return cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count, 0)
    })
    const selectedPrice = computed(() => {
        return cartList.value.filter(item => item.selected).reduce((a, c) => a + c.price * c.count, 0)
    })
    const clearCart = () => {
        cartList.value = []
    }
    return {
        cartList,
        addCart,
        delCart,
        allCount,
        allPrice,
        singCheck,
        isAll,
        allCheck,
        selectedCount,
        selectedPrice,
        clearCart
    }
}, {
    persist: true,
})